using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace GameForKids
{
    class FishGamePlay : DrawableGameComponent
    {

        // bien dem thoi gian
        public float milisecon = 0;
        // hien thi thoi gian choi
        public string timePlay = "";
        public int moved = 0;

        private SpriteFont helpFont;
        private SpriteFont font;

        // Game Object
        public List<Fish> Fishes;
        public int FishCount = 0;
        public int FishCatched = 0;
        public int FishLevelCount = 20;
        public int Level = 1;
        public float TimeToCreateFish = 2.0f;
        public float TotalTimeToCreateFish = 0.0f;
        public float TimeToCreateFishConst = 2.0f;
        private SoundEffect fishDisappearSound;

        // kiem tra cho phep play audio
        public bool isSound = true;


        // cong thuc tinh diem
        public static string CongThucGoc = "N*10/(20+L*5)";
        public static string CongThucHienTai = "";

        // tao co so du lieu
        private string strConnectionString = @"isostore:/FishGameDB.sdf";
        public FishGamePlay(Game game): base(game)
        {
            font = this.Game.Content.Load<SpriteFont>("Fonts/ChartFont");
            helpFont = this.Game.Content.Load<SpriteFont>("Fonts/HelpFont");
            fishDisappearSound = this.Game.Content.Load<SoundEffect>("FishGame/Sounds/FishDisappear");

            Fishes = new List<Fish>();


            // tao csdl
            using (ReadAndWrite readAndWriteDB = new ReadAndWrite(strConnectionString))
            {
                if (readAndWriteDB.DatabaseExists() == false)
                {
                    readAndWriteDB.CreateDatabase();
                }
            }


            // lay cong thuc
            using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isolatedStorageFile.FileExists("CongThuc" + GameForKids.gameState.ToString() + ".txt"))
                {
                    using (IsolatedStorageFileStream isfs = isolatedStorageFile.OpenFile("CongThuc" + GameForKids.gameState.ToString() + ".txt", FileMode.Open))
                    {
                        using (StreamReader reader = new StreamReader(isfs))
                        {
                            while (!reader.EndOfStream)
                            {
                                CongThucHienTai = reader.ReadLine();
                            }
                        }
                    }
                }
            }
            if (CongThucHienTai == "" || CongThucHienTai == null)
                CongThucHienTai = CongThucGoc;
        }
     
        // luu theo dang ID - ten  - level - diem - ngay
        public void saveScore(int score)
        {
            string _name = GameForKids.userName;
            int _level = FishGame.level;
            int _score = score;
            using (ReadAndWrite readAndWriteDB = new ReadAndWrite(strConnectionString))
            {
                DataScore newscore = new DataScore { 
                    ID = DateTime.Now.ToString(),
                    name = _name, 
                    level = _level, 
                    score = _score, 
                    day = DateTime.Today.ToShortDateString() };
                readAndWriteDB.TableScore.InsertOnSubmit(newscore);
                readAndWriteDB.SubmitChanges();
            }
        }

        private IList<DataScore> getListDataScore(string _name, int _level)
        {
            IList<DataScore> listDataScore = null;
            using (ReadAndWrite readAndWrite = new ReadAndWrite(strConnectionString))
            {
                IQueryable<DataScore> dataScoreQuery = from data in readAndWrite.TableScore where data.name.Equals(_name) && data.level == _level select data;
                listDataScore = dataScoreQuery.ToList();
            }
            return listDataScore;
        }

        public void startNewLevel(int _level)
        {
            ChartScreen.listDataScore = this.getListDataScore(GameForKids.userName, _level);
            ChartScreen.levelOfGame = _level;
            Level = _level;
            milisecon = 0;
            moved = 0;
            FishCatched = 0;
            FishCount = 0;
            FishLevelCount = (int)(20 + (_level * 5));
            TimeToCreateFish = TimeToCreateFishConst;
            TotalTimeToCreateFish = 0.0f;
            foreach (Fish fish in Fishes)
            {
                fish.Living = false;
            }
        }

        private void CreateNewFish()
        {
            bool done = false;
            int i = Suport.Random.Next(1, 11);
            int live = Level/5 + 1;
            switch (i)
            {
                case 1:
                case 2:
                case 3:
                case 4:
                    foreach (Fish fish in Fishes)
                    {
                        if (fish.Living == false && fish.Disappear == false && fish.TextureLink.CompareTo("FishGame/Images/FishNum1") == 0)
                        {
                            fish.Reset(RandomCenterPosition(), new Vector2(Suport.Random.Next(2, 5) + Level * 0.25f, 0), live);
                            done = true;
                            break;
                        }
                    }
                    if (done == false)
                    {
                        FishNum1 fish = new FishNum1(RandomCenterPosition(), new Vector2(Suport.Random.Next(2, 5) + Level * 0.25f, 0), live);
                        Fishes.Add(fish);
                    }
                    break;
                case 5:
                case 6:
                case 7:
                    foreach (Fish fish in Fishes)
                    {
                        if (fish.Living == false && fish.Disappear == false && fish.TextureLink.CompareTo("FishGame/Images/FishNum2") == 0)
                        {
                            fish.Reset(RandomCenterPosition(), new Vector2(Suport.Random.Next(3, 7) + Level * 0.30f, 0), live);
                            done = true;
                            break;
                        }
                    }
                    if (done == false)
                    {
                        FishNum2 fish = new FishNum2(RandomCenterPosition(), new Vector2(Suport.Random.Next(3, 7) + Level * 0.30f, 0), live);
                        Fishes.Add(fish);
                    }
                    break;
                case 8:
                    foreach (Fish fish in Fishes)
                    {
                        if (fish.Living == false && fish.Disappear == false && fish.TextureLink.CompareTo("FishGame/Images/FishNum3") == 0)
                        {
                            fish.Reset(RandomCenterPosition(), new Vector2(Suport.Random.Next(2, 4) + Level * 0.07f, 0), live);
                            done = true;
                            break;
                        }
                    }
                    if (done == false)
                    {
                        FishNum3 fish = new FishNum3(RandomCenterPosition(), new Vector2(Suport.Random.Next(2, 4) + Level * 0.07f, 0), live);
                        Fishes.Add(fish);
                    }
                    break;
                case 9:
                    foreach (Fish fish in Fishes)
                    {
                        if (fish.Living == false && fish.Disappear == false && fish.TextureLink.CompareTo("FishGame/Images/FishNum4") == 0)
                        {
                            fish.Reset(RandomCenterPosition(), new Vector2(Suport.Random.Next(10, 15) + Level * 0.7f, 0), live);
                            done = true;
                            break;
                        }
                    }
                    if (done == false)
                    {
                        FishNum4 fish = new FishNum4(RandomCenterPosition(), new Vector2(Suport.Random.Next(10, 15) + Level * 0.7f, 0), live);
                        Fishes.Add(fish);
                    }
                    break;
                case 10:
                    foreach (Fish fish in Fishes)
                    {
                        if (fish.Living == false && fish.Disappear == false && fish.TextureLink.CompareTo("FishGame/Images/FishNum5") == 0)
                        {
                            fish.Reset(RandomCenterPosition(), new Vector2(Suport.Random.Next(3, 5) + Level * 0.15f, 0), live);
                            done = true;
                            break;
                        }
                    }
                    if (done == false)
                    {
                        FishNum5 fish = new FishNum5(RandomCenterPosition(), new Vector2(Suport.Random.Next(3, 5) + Level * 0.15f, 0), live);
                        Fishes.Add(fish);
                    }
                    break;
            }
        }

        private Vector2 RandomCenterPosition()
        {
            Vector2 temp = new Vector2();
            temp.Y = Suport.Random.Next(100, 430);
            if (Suport.Random.Next(0, 100) % 2 == 0)
            {
                temp.X = -100;
            }
            else
            {
                temp.X = 900;
            }

            return temp;
        }

        //tinh diem
        public int getScore()
        {
            int mark = 0;
            XuLyCongThuc xulycongthuc;
            string s = "";

            xulycongthuc = new XuLyCongThuc();
            s = xulycongthuc.TinhDiem(CongThucHienTai, moved, (int)(milisecon / 1000), FishGame.level);
            double d = double.Parse(s);
            mark = (int)d;

            if (mark >= 10)
                return 10;
            if (mark <= 0)
                mark = 0;
            return mark;
        }

     
        public bool checkComplete()
        {
            foreach (Fish fish in Fishes)
            {
                if (fish.Living == true || fish.Disappear == true)
                {
                    return false;
                }
            }
            if (FishCount >= FishLevelCount)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public override void Initialize()
        {
            base.Initialize();
        }

        public void setTimePlay()
        {
            timePlay = ((int)milisecon / 60000).ToString() + " : " + (((int)milisecon / 1000) % 60).ToString();
        }

        public override void Update(GameTime gameTime)
        {
            TotalTimeToCreateFish += (float)gameTime.ElapsedGameTime.Milliseconds/1000.0f;
           
            float elapsed = (float)gameTime.ElapsedGameTime.Milliseconds;
            milisecon += elapsed;
           setTimePlay();

            // update fish
            foreach (Fish fish in Fishes)
            {
                fish.Update(gameTime);
            }

            if (TotalTimeToCreateFish >= TimeToCreateFish)
            {
                if (FishCount < FishLevelCount)
                {
                    CreateNewFish();
                    FishCount++;
                    TimeToCreateFish = TimeToCreateFishConst / ((float)(Level + 1)) + (((TimeToCreateFish * 0.95f) * ((float)Level)) / ((float)(Level + 1)));
                }
                TotalTimeToCreateFish = 0.0f;
            }


            base.Update(gameTime);
        }

        public virtual void Draw(GameTime gametime, SpriteBatch spriteBatch)
        {
            foreach (Fish fish in Fishes)
            {
                fish.Draw(spriteBatch);
            }

            spriteBatch.DrawString(helpFont, timePlay, new Vector2(10, 250), Color.White);
            spriteBatch.DrawString(helpFont, moved.ToString(), new Vector2(740, 250), Color.White);
        
        }

        public void TouchEvent(TouchLocation touch)
        {
            foreach (Fish fish in Fishes)
            {
                if (fish.Living == true)
                {
                    if (fish.IsHit(touch) == true)
                    {
                        fish.DoOnLiveDown();
                        if (GameForKids.ISMUSIC)
                        {
                            fishDisappearSound.Play();
                        }
                        if (fish.Living == false)
                        {
                            FishCatched++;
                            moved++;
                        }
                        break;
                    }

                }
            }
        }
    }
}
